package be.dch.csv.processor;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.apache.log4j.Logger;

import be.dch.csv.validator.CellValidator;
import be.dch.exceptions.ValidationException;
import be.dch.util.StringUtils;

public class DateProcessor extends AbstractCellProcessor {

    private static final Logger LOG = Logger.getLogger(DateProcessor.class);

    private transient final SimpleDateFormat formatter;

    public DateProcessor(final String format) {
	super();
	this.formatter = new SimpleDateFormat(format, Locale.getDefault());
    }

    public DateProcessor(final CellValidator validator, final String format) {
	super(validator);
	this.formatter = new SimpleDateFormat(format, Locale.getDefault());
    }

    @Override
    public Object parse(final String input) {
	Date result = null;
	try {
	    if (this.getValidator() == null) {
		result = this.formatter.parse(input);
	    } else if (!StringUtils.isEmpty(input)) {

		try {
		    this.getValidator().validate(input);
		    result = this.formatter.parse(input);
		} catch (final ValidationException e) {
		    DateProcessor.LOG.warn(e);
		}
	    }
	} catch (final ParseException e) {
	    DateProcessor.LOG.warn(e.getMessage());
	}
	return result;

    }
}
